﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using zyzyzy1.Models;

namespace zyzyzy1.Controllers
{
    public class DefaultController : Controller
    {
        Model1 model = new Model1();
        public ActionResult Index(int DeviceID = 0, string Content = "",int DefectState=0)
        {
            var list = model.Device.ToList();
            list.Insert(0, new Device() { DeviceName = "全部", DeviceID = 0 });
            ViewBag.DeviceID = new SelectList(list, "DeviceID", "DeviceName");
            var l = model.Defect.Where(p => (DeviceID == 0 || p.DeviceID == DeviceID)&& (p.Content.Contains(Content)) && (DefectState ==0||p.DefectState== DefectState)).ToList();
            return View(l);

        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <returns></returns>
        public ActionResult Create()
        {

            ViewBag.DeviceID = new SelectList(model.Device, "DeviceID", "DeviceName");
            return View();
        }
        [HttpPost]
        public ActionResult Create(Defect defect)
        {
            if (ModelState.IsValid)
            {
                defect.AddTime = DateTime.Now;
                defect.DefectState = 1;
                defect.DealTime = null;

                model.Defect.Add(defect);
                var res = model.SaveChanges();
                if (res > 0)
                {
                    return RedirectToAction("Index");

                }
            }
            ViewBag.DeviceID = new SelectList(model.Device, "DeviceID", "DeviceName");
            return View(defect);
        }
       
        public ActionResult Delete(int ? id) {
            if(id==null){
                return Json(false);
            }
            var task = model.Defect.FirstOrDefault(p=>p.DefectID==id);
            if (task==null) {
                return Json(false);
            }
            model.Defect.Remove(task);
            var u = model.SaveChanges();
            return Json(u>0);
        
        }
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return Json(false);
            }
            var task = model.Defect.FirstOrDefault(p => p.DefectID == id);
            if (task == null)
            {
                return Json(false);
            }

            task.DefectState = 2;
            task.DealTime = DateTime.Now;
            var u = model.SaveChanges();
            return Json(u > 0);

        }
    }
}